package com.dl7.mvp.music.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Icon;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.PowerManager;
import android.os.Process;
import android.support.v4.app.NotificationCompat;
import android.widget.RemoteViews;

import com.dl7.mvp.MainActivity;
import com.dl7.mvp.music.bean.MusicInfo;
import com.dl7.mvp.music.ui.QuickControlsFragment;
import com.dl7.mvp.mvp.R;
import com.dl7.mvp.utils.NotificationUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Bear on 2015/8/7.
 */
public class MusicService extends Service implements MediaPlayer.OnCompletionListener {
    private MusicInfo mPlayingMusicInfo;

    public interface IMusicChangeListener {
        void onMusicChange(MusicInfo info);
    }

    //为日志工具设置标签
    private static String TAG = "MusicService";
    //定义音乐播放器变量
    private MediaPlayer mMediaPlayer;
    private PlayerBinder mBinder;
    private ArrayList<MusicInfo> mMusicList;
    private int mCurrentIndex;

    private List<IMusicChangeListener> mListenerList = new ArrayList<>();
    private ServiceHandler mHandler;

    @Override
    public void onCreate() {
        super.onCreate();
        mBinder = new PlayerBinder();
        initPlayer();
        registerReceiver();

        // 默认情况下Service是运行在主线程中，而服务一般又十分耗费时间，如果
        // 放在主线程中，将会影响程序与用户的交互，因此把Service
        // 放在一个单独的线程中执行
        HandlerThread thread = new HandlerThread("MessageDemoThread", Process.THREAD_PRIORITY_BACKGROUND);
        thread.start();
        // 获取当前线程中的looper对象
        //创建Handler对象，把looper传递过来使得handler、
        //looper和messageQueue三者建立联系
        mHandler = new ServiceHandler(thread.getLooper());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        release();
        cancelNotification();
        mHandler = null;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    private MusicInfo getNext(boolean init) {
        if (mMusicList != null && mMusicList.size() > 0) {
            if (!init) {
                mCurrentIndex++;
            }
            if (mCurrentIndex >= mMusicList.size()) {
                mCurrentIndex = 0;
            }
            return mMusicList.get(mCurrentIndex);
        }
        return null;
    }

    private MusicInfo getPrev(boolean init) {
        if (mMusicList != null && mMusicList.size() > 0) {
            if (!init) {
                mCurrentIndex--;
            }
            if (mCurrentIndex < 0) {
                mCurrentIndex = mMusicList.size() - 1;
            }
            return mMusicList.get(mCurrentIndex);
        }
        return null;
    }

    private void initPlayer() {
        if (mMediaPlayer == null) {
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setLooping(true);
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mMediaPlayer.setOnCompletionListener(this);
            mMediaPlayer.setWakeMode(this, PowerManager.PARTIAL_WAKE_LOCK);
        }
    }

    private void registerReceiver() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(TOGGLE_PLAY_ACTION);
        filter.addAction(NEXT_ACTION);
        filter.addAction(STOP_ACTION);
        registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (mMediaPlayer == null) {
                    return;
                }
                switch (intent.getAction()) {
                    case TOGGLE_PLAY_ACTION:
                        if (mMediaPlayer.isPlaying()) {
                            pause();
                        } else {
                            resume();
                        }
                        break;
                    case PREV_ACTION:
                        playNext();
                        break;
                    case NEXT_ACTION:
                        playNext();
                        break;
                    case STOP_ACTION:
                        release();
                        cancelNotification();
                        stopSelf();
                        break;
                }
            }
        }, filter);
    }

    private Notification mNotification;
    private int mNotiID = 100;
    public static final String TOGGLE_PLAY_ACTION = "com.wm.remusic.toggle_play";
    public static final String PREV_ACTION = "com.wm.remusic.prev";
    public static final String NEXT_ACTION = "com.wm.remusic.next";
    public static final String STOP_ACTION = "com.wm.remusic.stop";

    private void updateNotification() {

        NotificationUtils notificationUtils = new NotificationUtils(this);
        notificationUtils.sendNotification("测试标题", "测试内容");

        RemoteViews remoteViews;
        final boolean isPlaying = mMediaPlayer.isPlaying();

        remoteViews = new RemoteViews(this.getPackageName(), R.layout.music_controller);
        remoteViews.setTextViewText(R.id.music_title, mPlayingMusicInfo.getName());

        //此处action不能是一样的 如果一样的 接受的flag参数只是第一个设置的值
        Intent pauseIntent = new Intent(TOGGLE_PLAY_ACTION);
        PendingIntent pausePIntent = PendingIntent.getBroadcast(this, 0, pauseIntent, 0);
        remoteViews.setImageViewResource(R.id.iv_pause, isPlaying ? R.drawable.desk_pause : R.drawable.desk_play);
        remoteViews.setOnClickPendingIntent(R.id.iv_pause, pausePIntent);

        Intent nextIntent = new Intent(NEXT_ACTION);
        PendingIntent nextPIntent = PendingIntent.getBroadcast(this, 0, nextIntent, 0);
        remoteViews.setImageViewResource(R.id.iv_pause, R.drawable.desk_next);
        remoteViews.setOnClickPendingIntent(R.id.iv_next, nextPIntent);

        Intent preIntent = new Intent(STOP_ACTION);
        PendingIntent prePIntent = PendingIntent.getBroadcast(this, 0, preIntent, 0);
        remoteViews.setOnClickPendingIntent(R.id.iv_stop, prePIntent);

        final Intent nowPlayingIntent = new Intent();
        nowPlayingIntent.setClass(this, MainActivity.class);
        nowPlayingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent click = PendingIntent.getActivity(this, 0, nowPlayingIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        if (mNotification == null) {
            Notification.Builder builder = new Notification.Builder(getApplicationContext())
                    .setContentText("通知内容")
                    .setContentTitle("通知标题")
                    .setSmallIcon(R.drawable.ic_launcher_round)
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_round))
                    .setWhen(System.currentTimeMillis())
                    .setContentIntent(click);
            mNotification = builder.build();
        } else {
            mNotification.contentView = remoteViews;
        }

        NotificationChannel channel = new NotificationChannel(String.valueOf(mNotiID), "erge", NotificationManager.IMPORTANCE_HIGH);
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.createNotificationChannel(channel);
        manager.notify(mNotiID, mNotification);

        showNotificationProgress(getApplicationContext());
    }

    public void showNotificationProgress(Context context) {
        RemoteViews mRemoteViews;
        /**进度条通知构建**/
        NotificationCompat.Builder builderProgress = new NotificationCompat.Builder(context);
        /**设置为一个正在进行的通知**/
        builderProgress.setOngoing(true);
        /**设置小图标**/
        builderProgress.setSmallIcon(R.drawable.ic_launcher);

        /**新建通知自定义布局**/
        mRemoteViews = new RemoteViews(context.getPackageName(), R.layout.notification);
        /**进度条ProgressBar**/
        /**提示信息的TextView**/
        mRemoteViews.setTextViewText(R.id.music_title, "下载中...");
        /**设置左侧小图标*/
        mRemoteViews.setImageViewResource(R.id.music_img, R.drawable.ic_launcher);
        /**设置通过广播形式的PendingIntent**/
        /**设置自定义布局**/
        builderProgress.setContent(mRemoteViews);
        /**设置滚动提示**/
        builderProgress.setTicker("开始下载...");
        Notification notification = builderProgress.build();
        /**设置不可手动清除**/
        notification.flags = Notification.FLAG_NO_CLEAR;
        /**获取通知管理器**/
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
        /**发送一个通知**/
        notificationManager.notify(22, notification);
    }

    private void cancelNotification() {
        if (mNotification != null) {
            NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            manager.cancel(mNotiID);
            mNotification = null;
        }
    }

    private void playMusic(MusicInfo info) {
        synchronized (this) {
            if (info == null || info.getUrl() == null || mMediaPlayer == null) {
                return;
            }

            try {
                // 切歌之前先重置，释放掉之前的资源
                mMediaPlayer.reset();
                // 设置播放源
                mMediaPlayer.setDataSource(info.getUrl());
                // 开始播放前的准备工作，加载多媒体资源，获取相关信息
                mMediaPlayer.prepare();
                // 开始播放
                mMediaPlayer.start();
            } catch (IOException e) {
                e.printStackTrace();
            }

            mPlayingMusicInfo = info;
            for (IMusicChangeListener musicChangeListener : mListenerList) {
                musicChangeListener.onMusicChange(info);
            }
            //updateNotification();
        }
    }

    public void pause() {
        synchronized (this) {
            if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
                mMediaPlayer.pause();
            }
        }
    }

    public void resume() {
        synchronized (this) {
            if (mMediaPlayer != null && !mMediaPlayer.isPlaying()) {
                mMediaPlayer.start();
            }
        }
    }

    public void release() {
        synchronized (this) {
            if (mMediaPlayer != null) {
                mMediaPlayer.stop();
                mMediaPlayer.release();
                mMediaPlayer = null;
            }
        }
    }

    public void playNext() {
        playMusic(getNext(false));
    }

    public void playPrev() {
        playMusic(getPrev(false));
    }

    public int getDuration() {
        return mMediaPlayer.getDuration();
    }

    public int getCurrentPosition() {
        return mMediaPlayer.getCurrentPosition();
    }

    public boolean isPlaying() {
        return mMediaPlayer != null && mMediaPlayer.isPlaying();
    }

    public class PlayerBinder extends Binder {
        public void registerMusicChangeListener(IMusicChangeListener listener) {
            mListenerList.add(listener);
            if (listener != null && mPlayingMusicInfo != null && isPlaying()) {
                listener.onMusicChange(mPlayingMusicInfo);
            }

        }
        public void setMusicList(ArrayList<MusicInfo> list, int index) {
            mMusicList = list;
            mCurrentIndex = index;
            if (mHandler != null) {
                mHandler.removeMessages(0);
                mHandler.sendEmptyMessageDelayed(0, 300);
            }
        }

        public void pause() {
            MusicService.this.pause();
        }

        public void resume() {
            MusicService.this.resume();
        }

        public void release() {
            MusicService.this.release();
        }

        public void playNext() {
            MusicService.this.playNext();
        }

        public void playPrev() {
            MusicService.this.playPrev();
        }

        public int getDuration() {
            return MusicService.this.getDuration();
        }

        public int getCurrentPosition() {
            return MusicService.this.getCurrentPosition();
        }

        public boolean isPlaying() {
            return MusicService.this.isPlaying();
        }
        public boolean isReadyForPlay() {
            return MusicService.this.isReadyForPlay();
        }
    }

    private boolean isReadyForPlay() {
        return mPlayingMusicInfo != null;
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        playMusic(getNext(false));
    }


    private final class ServiceHandler extends Handler
    {
        public ServiceHandler(Looper looper)
        {
            super(looper);
        }

        @Override
        public void handleMessage(Message msg)
        {
            // 根据what字段判断是哪个消息
            switch (msg.what)
            {
                case 0:
                    playMusic(getNext(true));
                    break;
                // other cases
                default:
                    break;
            }
        }
    }

}